const jwt = require('jsonwebtoken');

let setToken = function (str1, str2) {
    let user = str1;
    let paswd = str2;
    const rule = {
        username: user,
        pwd: paswd
    };
    let secret = 'Andy';
    let ztoken = jwt.sign(rule, secret, { expiresIn: 60 * 60 * 24 });
    return ztoken;
};
let getToken = function (token) {
    if (token) {
        try {
            let decoded = jwt.verify(token, 'Andy');
            if(decoded.username!=='admin'){
                return { boolean: true, msg: '验证通过', decoded: decoded , isAdmin:false};
            }
            return { boolean: true, msg: '验证通过', decoded: decoded , isAdmin:true};
            
        } catch (error) {
            if (error.name === 'TokenExpiredError') {
                return { boolean: false, msg: '令牌过期' };
            } else {
                return { boolean: false, msg: `验证失败 ${error.message}` };
            }
        }
    }
    return { boolean: false, msg: '请传递Token' };
};
module.exports = { setToken, getToken };
